<template>
  <div class="cell-switch-box">
    <span v-if="handleAuth">{{ scopeData.row[tableItem.prop] }}</span>
    <el-switch
      v-else
      v-model="value"
      :disabled="isDisabledBtn(tableItem, scopeData.row)"
      :width="55"
      :class="tableItem.componentCellClass||'on-off-text'"
      active-color="rgb(219,139,57)"
      v-bind="tableItem.attrConfig||{}"
      :active-text="tableItem.switchConfig['activeName']"
      :inactive-text="tableItem.switchConfig['inactiveName']"
      @change="switchChange"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { MessageBox } from 'element-ui'

export default {
  name: 'CellSwitch',
  props: {
    // 单元格数据
    scopeData: {
      type: Object,
      default: () => ({})
    },
    // 单元格配置项
    tableItem: {
      type: Object,
      default: () => ({})
    },
    // 表格数据
    tableData: {
      type: Object,
      default: () => ({})
    },
    // 刷新单元格
    refeshCell: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      value: false
    }
  },
  computed: {
    ...mapGetters([
      'authList'
    ]),
    handleAuth() {
      const { authId } = this.tableItem || {}
      if (authId) {
        return !this.authList.find(f => f.permission === authId)
      }
      return false
    },
    isDisabledBtn() {
      return (btnItem, row) => {
        const { disabledRules } = btnItem || {}
        if (disabledRules) {
          const { type = 'find', ruleList = [] } = disabledRules
          if (type === 'find') {
            return !!ruleList.find(e => row[e.prop] === e.value)
          } else {
            return !!ruleList.every(e => row[e.prop] === e.value)
          }
        }
        return false
      }
    }
  },
  watch: {
    refeshCell() {
      const { row } = this.scopeData || {}
      const { switchConfig = {} } = this.tableItem || {}
      this.value = !![switchConfig.activeCode, switchConfig.activeName].includes(row[switchConfig.dataProp])
    }
  },
  mounted() {
    const { row } = this.scopeData || {}
    const { switchConfig = {} } = this.tableItem || {}
    this.value = !![switchConfig.activeCode, switchConfig.activeName].includes(row[switchConfig.dataProp])
  },
  methods: {
    /**
     * 开关变化
     */
    switchChange() {
      const { row } = this.scopeData || {}
      const { switchConfig = {} } = this.tableItem || {}
      const {
        switchPath,
        activeCode,
        inactiveCode,
        activeName,
        inactiveName,
        switchParamsProp = {},
        dataProp,
        valueTypeProp
      } = switchConfig
      let curVal = this.value ? activeCode : inactiveCode
      if (valueTypeProp === 'name') {
        curVal = this.value ? activeName : inactiveName
      }
      const parmas = {
        [dataProp]: curVal
      }
      Object.keys(switchParamsProp).forEach(key => {
        parmas[key] = row[key]
      })
      if (switchConfig.confirmHeader != null && switchConfig.confirmContent != null) {
        MessageBox.confirm(`${switchConfig.confirmContent}`, `${switchConfig.confirmHeader}`, {
          confirmButtonText: `${switchConfig.confirmButtonText || '确认'}`,
          cancelButtonText: `${switchConfig.cancelButtonText || '取消'}`,
          customClass: 'set-max-height50',
          dangerouslyUseHTMLString: true,
          type: 'warning'
        })
          .then(() => {
            this.update(parmas, switchPath)
          })
          .catch(() => {
            this.value = !curVal
          })
      } else {
        this.update(parmas, switchPath)
      }
    },
    /**
     * 更新
     */
    async update(params, path) {
      if (!path) {
        return
      }

      const { switchConfig = {} } = this.tableItem || {}
      const {
        activeCode,
        inactiveCode,
        activeName,
        inactiveName,
        dataProp,
        valueTypeProp
      } = switchConfig

      try {
        const newPath = path.split('.')
        let api = this.$api
        newPath.forEach(e => {
          api = api[e]
        })
        const res = await api(params)
        if (Number(res.code) === 1000) {
          this.$message.success('修改成功!')
        } else if (res.msg) {
          this.value = !this.value
          // this.$message({ type: 'error', message: res.msg })
        }
      } catch (error) {
        this.value = !this.value
      }

      const codeVal = this.value ? activeCode : inactiveCode
      const nameVal = this.value ? activeName : inactiveName
      if (valueTypeProp === 'name') {
        this.$set(this.scopeData.row, dataProp.replace('Name', ''), codeVal)
        this.$set(this.scopeData.row, dataProp, nameVal)
      } else {
        this.$set(this.scopeData.row, dataProp, codeVal)
        this.$set(this.scopeData.row, `${dataProp}Name`, nameVal)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.cell-switch-box {
  width: 90%;
}
</style>
